package com.aneliya.history;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

import com.aneliya.model.Message;

public class HistoryManager {

	private static HistoryManager instance;

	public static HistoryManager getInstance() {
		if (instance == null) {
			instance = new HistoryManager();
		}
		return instance;
	}

	protected HistoryManager() {
		
	}
	
	public void saveArrayList(String id, ArrayList<Message> arrayList, int count ) {
		try {
			FileOutputStream fileOutputStream = new FileOutputStream(id);
			ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
			
			ArrayList<Message> sublist = new ArrayList<Message>(
					arrayList.subList(Math.max(0, arrayList.size() - count), arrayList.size()));
			
			objectOutputStream.writeObject(sublist);		
			
			objectOutputStream.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
	
	@SuppressWarnings("unchecked")
	public void retrieveArrayList(String id, ArrayList<Message> arrayList) {
		try {
			File file = new File(id);
			if (!file.exists()) {
				return;
			}
			
			FileInputStream fileInputStream = new FileInputStream(id);
			ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
			
			ArrayList<Message> serializedArrayList = (ArrayList<Message>)objectInputStream.readObject();
			arrayList.addAll(serializedArrayList);
					
			objectInputStream.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		} catch (ClassNotFoundException ex) {
			ex.printStackTrace();
		}
		
	}
	
}
